class Solution 
{
    int m{}, n{};
    bool visit[1001][1001]{};
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
public:
    int rotApple(vector<vector<int> >& grid) 
    {
        m = grid.size(), n = grid[0].size();
        queue<pair<int, int>> q;
        for(int i=0; i<m; i++)
        {
            for(int j=0; j<n; j++)
            {
                if(grid[i][j] == 2)
                {
                    q.emplace(i, j);
                    visit[i][j] = true;
                }
            }
        }

        int time = 0;
        while(!q.empty())
        {
            time++;
            int sz = q.size();
            while(sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for(int k=0; k<4; k++)
                {
                    int x = a+dx[k], y = b+dy[k];
                    if(x>=0 && x<m && y>=0 && y<n && !visit[x][y] && grid[x][y]==1)
                    {
                        grid[x][y] = 2;
                        q.emplace(x, y);
                        visit[x][y] = true;
                    }
                }
            }
        }

        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                if(grid[i][j] == 1)
                    return -1;
        return time-1;
    }
};